package com.ckm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckm.dto.StudentCourseInfoDto;
import com.ckm.entity.Course;
import com.ckm.entity.Student;
import com.ckm.entity.StudentCourse;
import com.ckm.entity.TeacherCourse;
import com.ckm.exception.BusinessException;
import com.ckm.mapper.CourseMapper;
import com.ckm.mapper.StudentCourseMapper;
import com.ckm.mapper.TeacherCourseMapper;
import com.ckm.service.StatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Service
public class StatisticServiceImpl implements StatisticService {

    @Autowired
    private StudentCourseMapper studentCourseMapper;
    @Autowired
    private TeacherCourseMapper teacherCourseMapper;
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<?> allScore(List<Student> studentList, Date date ,List<Course> courseList) {
        HashMap<String, List<StudentCourse>> studentScoreMap = new HashMap<>();
        for (Student student : studentList) {
            QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<StudentCourse>()
                    .eq("stu_id", student.getId())
                    .eq("create_time", date);
            List<StudentCourse> studentCourseList = studentCourseMapper.selectList(queryWrapper);
            if (studentCourseList.isEmpty()) {
                log.warn("学生：{}，在{}考试中无成绩",student.getName(),date);
//                continue;
            }
            studentScoreMap.put(student.getName(),
                    studentCourseList.stream()
                            .sorted(Comparator.comparing(StudentCourse::getTchCourseId))
                            .toList());
        }
        //k:学生名，v：学生课程成绩列表
        LinkedList<Map<String, Object>> result = new LinkedList<>();
        studentScoreMap.forEach((k,v)->{
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("studentName",k);
            AtomicReference<Float> totalScore = new AtomicReference<>((float) 0);
            courseList.forEach(c->{
                if (v.isEmpty()){
                    map.put(c.getCourseName(),null);
                }
                v.forEach(v1->{
                    TeacherCourse teacherCourse = teacherCourseMapper.selectById(v1.getTchCourseId());
                    if (teacherCourse == null) {
                        log.warn("教师课程查找失败：{}",v1.getTchCourseId());
                    }else {
                        Course course = courseMapper.selectById(teacherCourse.getCourseId());
                        if (course == null) {
                            log.warn("课程查找失败：{}",teacherCourse.getCourseId());
                        }else {
                            if (c.getCourseName().equals(course.getCourseName())) {
                                if (v1.getScore()==null){
                                    log.warn("学生:{},课程:{},成绩未打分",k,course.getCourseName());
                                    map.put(course.getCourseName(),null);
                                }else {
                                    map.put(course.getCourseName(),v1.getScore());
                                    totalScore.updateAndGet(v2 -> v2 + v1.getScore());
                                }
                            }else {
                                map.put(c.getCourseName(),null);
                            }
                        }
                    }
                });
            });

            map.put("totalScore",totalScore.get());
            result.add(map);
        });
        rankStudentScore(result);
        return result;
    }

    @Override
    public List<?> singleCourseScore(List<Student> studentList, Date date, String courseName) {
        ArrayList<Course> list = new ArrayList<>();
        Course course = courseMapper.selectOne(new QueryWrapper<Course>().eq("course_name", courseName));
        if (course == null) {
            throw new BusinessException(250,"无此课程");
        }
        list.add(course);
        return allScore(studentList, date, list);
    }

    @Override
    public void gradeAllScore(Integer gradeId) {

    }

    @Override
    public void gradeSingleCourseScore(Integer gradeId, Integer courseId) {

    }

    @Override
    public void rankStudentScore(List<Map<String, Object>> list) {
        ArrayList<StudentCourseInfoDto> arrayList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            StudentCourseInfoDto studentCourseInfoDto = new StudentCourseInfoDto();
            studentCourseInfoDto.setScore((Float) map.get("totalScore"));
            studentCourseInfoDto.setStudentName(map.get("studentName").toString());
            arrayList.add(studentCourseInfoDto);
        }
        HashMap<String, Object> map = new HashMap<>();
        List<StudentCourseInfoDto> rankList = arrayList.stream().sorted(Comparator.comparing(StudentCourseInfoDto::getScore).reversed()).toList();
        for (int i = 0; i < rankList.size(); i++) {
            map.put(rankList.get(i).getStudentName(),i+1);
        }
        for (Map<String, Object> objectMap : list) {
            objectMap.put("rank",map.get(objectMap.get("studentName").toString()));
        }
    }
}
